import sqlite3

from Mode import Example
from Mode.Log import Log

Tag = "SQLite"


class SQLite(object):
    # 初始化数据库 2021/12/11 21:01 By Wangxc_a_bj
    def __init__(self, db):
        self.conn = sqlite3.connect(db)
        # print(self.conn)
        # self.conn.execute("select name from sqlite_master where type='table' order by name")
        # print(self.conn.fetchall())
        self.c = self.conn.cursor()

    def select(self, table_name, value: Example = None):
        if value and len(value.getStr()) != 0:
            Str = " and ".join(value.getStr())
            sql = f"select * from {table_name} where {Str}"
        else:
            sql = f"select * from {table_name}"
        # sql = f"select * from {table_name} where 1=1"
        Log(Tag, f"执行sql语句:{sql}")
        cursor = self.c.execute(sql)
        result = []
        for row in cursor:
            result.append(row)
        return result
        # pass

    def insertInto(self,table_name,params:dict):
        Keys = list(params.keys())
        sql = f"INSERT INTO {table_name} ({','.join()})VALUES (value1,value2,value3,...);"
        cursor = self.c.execute(sql)
        self.conn.commit()
    def update(self,sql):
        cursor = self.c.execute(sql)
        self.conn.commit()

    def exec(self,sql):
        cursor = self.c.execute(sql)
        self.conn.commit()
        result = []
        for row in cursor:
            result.append(row)
        return result

    # 关闭数据库连接 2021/12/11 21:01 By Wangxc_a_bj
    def __del__(self):
        self.conn.close()


SQLite("Data.db")
